#!/usr/bin/python2.5

import os
import sys
import wsgiref.handlers

from django.utils import simplejson

from google.appengine.ext import db
from google.appengine.ext import webapp

from geo import geotypes

from models import Rental
import errors


def _merge_dicts(*args):
  """Merges dictionaries right to left. Has side effects for each argument."""
  return reduce(lambda d, s: d.update(s) or d, args)


class SearchService(webapp.RequestHandler):
  """Handler for rental property search."""
  def get(self):
    
    self.response.headers['Content-Type'] = 'application/json'
    
    try:
      center = geotypes.Point(float(self.request.get('lat')),
                            float(self.request.get('lon')))
    except ValueError:
        return errors.error(errors.INVALID_LAT_OR_LON, "%s, %s" % (self.request.get('lat'), self.request.get('lon')))
    
    max_results = 100
    max_distance = 3000 # 3 km ~ 2 mi

    try:
      base_query = Rental.all()

      results = Rental.proximity_fetch(
            base_query,
            center, max_results=max_results, max_distance=max_distance)
      
      self.response.out.write(simplejson.dumps({
        'status': 'success',
        'results': results_obj
      }))
    except:
      return errors.error(errors.SERVICE_UNAVAILABLE, e.reason, 503)

